import { Injectable } from '@angular/core';
import { Http, URLSearchParams } from '@angular/http';

import { GAService } from '../services/ga.service';
import { RiskBaseService } from '../services/riskBase.service';

@Injectable()
export class RiskBaseComponent {
    private companyClusters: any[] = null;
    private meiClusters: any[] = null;
    private readonly riskBaseService: RiskBaseService;

    public loaded: Promise<void>;    
    public readonly gaService: GAService = new GAService();    
    public readonly clusterMetadata: any =
    {
        X: { color: '#FCEDCC', shortName: 'Negligible'},
        A: { color: '#F9DD99', shortName: 'Low'},
        B: { color: '#F6CD66', shortName: 'Med'},
        C: { color: '#F3BC33', shortName: 'High'},
        D: { color: '#F0AB01', shortName: 'Severe'}
    };

    constructor(protected baseHttp: Http) {
        //read risk clusters
        this.riskBaseService = new RiskBaseService(baseHttp);        
    }

    public getCompanyClusters(): Promise<any[]> {
        let promise = new Promise<any[]>((resolve, reject) => {
            if (this.companyClusters == null) {                
                this.riskBaseService.getCompanyRiskClusters().then(data => {
                    this.companyClusters = this.prepareCluster(data);
                    resolve(this.companyClusters);
                });            
            }
            else
                resolve(this.companyClusters);
        });
        return promise;
    }

    public getMeiClusters(): Promise<any[]> {
        let promise = new Promise<any[]>((resolve, reject) => {
            if (this.meiClusters == null) {                
                this.riskBaseService.getMeiRiskClusters().then(data => {
                    this.meiClusters = this.prepareCluster(data);
                    resolve(this.meiClusters);
                });            
            }
            else
                resolve(this.meiClusters);
        });
        return promise;
    }

    private prepareCluster(clusters: any[]): any[] {
        var result: any[] = [];
        for (var i in clusters)
            result.push({
                id: clusters[i].assessment,
                code: clusters[i].code,
                name: clusters[i].name,
                shortName: this.clusterMetadata[clusters[i].code].shortName,
                color: this.clusterMetadata[clusters[i].code].color,
                topInterval: clusters[i].upperBound
            });
        return result;
    }

    public formatRank(rank: number) : string {        
        var strRank = rank.toString();
        return strRank + (strRank.endsWith("1") ? "st" : (strRank.endsWith("2") ? "nd": (strRank.endsWith("3")? "rd": "th")));
    }    

    public formatMeiWeight(value: number): number {
        return value * 100;
    }
}